package org.bdware.doip.core.doipMessage;

import org.bdware.doip.core.codec.DigitalObjectCodecImpl;
import org.bdware.doip.core.exception.DoDecodeException;
import org.bdware.doip.core.model.digitalObject.DigitalObject;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class MessageBody {

    //Body可能是Element，也可能是DigitalObject
    public byte[] encodedData;

    public MessageBody(){
        encodedData = new byte[0];
    }

    public int getLength(){
        return encodedData.length;
    }

    public void setDataAsDigitalObject(DigitalObject digitalObject){
        this.encodedData = new DigitalObjectCodecImpl().DoToByteArray(digitalObject);
    }

    public DigitalObject getDataAsDigitalObject() throws DoDecodeException, IOException {
        return new DigitalObjectCodecImpl().ByteArrayToDo(encodedData);
    }

    public String getDataAsJsonString(){
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(encodedData));
        // Json segment length
        int metaLen = 0;
        try {
            metaLen = input.readInt();
            if(metaLen != input.available()){
                input.reset();
                metaLen = input.available();
            }
            byte[] content = new byte[metaLen];
            input.read(content);
            return new String(content);
        } catch (Exception e) {
//            e.printStackTrace();
            return new String(encodedData);
        }
    }

    public byte[] getEncodedData(){
        return encodedData;
    }



}
